package com.michael.demos.springboot.ext.processor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.ScannedGenericBeanDefinition;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * 类功能描述:
 * <pre>
 *   xxxx
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2020/9/3 16:16
 */
@Slf4j
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        DefaultListableBeanFactory defaultBeanFactory = (DefaultListableBeanFactory) beanFactory;
        defaultBeanFactory.removeBeanDefinition("myBeanPostProcessor");
        // 通过beanFactory获取所有BeanDefinition名称
        List<String> definitionNames = Arrays.asList(defaultBeanFactory.getBeanDefinitionNames());
        for (String definitionName : definitionNames) {
            Object beanDefinition = beanFactory.getBeanDefinition(definitionName);
            if (beanDefinition instanceof ScannedGenericBeanDefinition) {
                ScannedGenericBeanDefinition bean = (ScannedGenericBeanDefinition) beanDefinition;
                AnnotationMetadata metadata = bean.getMetadata();
                log.info("AnnotationMetadata {} -> {}", definitionName, metadata.getClass());
            }
        }

        log.error("BeanFactoryPostProcessor.postProcessBeanFactory()");
        //beanFactory.
    }
}
